<template>
  <div>
    <el-container style="height: 700px; border: 1px solid #eee">
      <el-header style="font-size: 40px; background-color: rgb(238,241,246);">学生成绩管理系统</el-header>
      <el-container>
        <el-aside width="200px">
          <el-menu :default-openeds="['1', '3']">
            <el-submenu index="1">
              <template slot="title"><i class="el-icon-menu"></i>专业</template>
              <el-menu-item-group>
                <template slot="title">网安23级</template>
                <el-menu-item index="1-1">
                  <router-link to="/students" style="text-decoration: none;">学生管理</router-link>
                </el-menu-item>
                <el-menu-item index="1-2">
                  <router-link to="/score" style="text-decoration: none;">学生成绩</router-link>
                </el-menu-item>
              </el-menu-item-group>
            </el-submenu>
            <el-submenu index="2">
              <template slot="title"><i class="el-icon-message"></i>班级管理</template>
              <el-menu-item-group>
                <template slot="title">班级管理</template>
                <el-menu-item index="2-1">
                  <router-link to="/class" style="text-decoration: none;">班级管理</router-link>
                </el-menu-item>
              </el-menu-item-group>
            </el-submenu>
            <el-submenu index="3">
              <template slot="title"><i class="el-icon-message"></i>班级信息管理</template>
              <el-menu-item-group>
                <template slot="title">网安2311</template>
                <el-menu-item index="3-1">
                  <router-link to="/students" style="text-decoration: none;">学生管理</router-link>
                </el-menu-item>
                <el-menu-item index="3-2">
                  <router-link to="/score" style="text-decoration: none;">学生成绩</router-link>
                </el-menu-item>
              </el-menu-item-group>
              <el-menu-item-group title="网安2312">
                <el-menu-item index="3-3" style="text-decoration: none;">学生管理</el-menu-item>
                <el-menu-item index="3-4" style="text-decoration: none;">学生成绩</el-menu-item>
              </el-menu-item-group>
              <el-menu-item-group title="网安2313">
                <el-menu-item index="3-5" style="text-decoration: none;">学生管理</el-menu-item>
                <el-menu-item index="3-4" style="text-decoration: none;">学生成绩</el-menu-item>
              </el-menu-item-group>
            </el-submenu>
          </el-menu>
        </el-aside>
        <div>
          <!-- 将新增学生按钮移到此处，位于班级表格上方 -->
          <div style="display: flex; justify-content: flex-end;">
            <el-button type="primary" @click="handleAdd">新增班级</el-button>
          </div>
          <el-table :data="computedTableData" border>
            <el-table-column prop="name" label="班级" width="300"></el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="300"></el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="300"></el-table-column>
            <el-table-column label="操作" width="300">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            background
            layout="prev, pager, next"
            :total="totalData"
            :page-size="pageSize"
            :current-page="currentPage"
            :hide-on-single-page="true"
            @current-change="handlePageChange">
          </el-pagination>
          <el-dialog :visible.sync="addDialogVisible" title="新增班级">
            <el-form :model="newClass" label-width="80px">
              <el-form-item label="班级名">
                <el-input v-model="newClass.name"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitAdd">保存</el-button>
                <el-button @click="addDialogVisible = false">取消</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>
        </div>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      tableData: [],
      totalData: 0, // 总数据量
      pageSize: 10, // 展示数据量
      currentPage: 1, // 当前页
      addDialogVisible: false,
      newClass: {
        name: '',
        deptId: null
      }
    };
  },
  computed: {
    computedTableData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.tableData.slice(start, end);
    }
  },
  methods: {
    async handleSearch() {
      this.currentPage = 1;
      await this.fetchSearchData();
    },
    async handlePageChange(newpage) {
      this.currentPage = newpage;
      try {
        await this.fetchData();
        console.log('当前选中的页码是,' + newpage);
      } catch (error) {
        this.showError('请求失败，请检查网络或联系管理员');
      }
    },
    async fetchData() {
      try {
        const response = await axios.get('http://localhost:8080/class', {
          params: {
            page: this.currentPage,
            pageSize: this.pageSize
          }
        });
        const result = response.data;
        if (result.code === 1 && result.msg === "success" && result.data) {
          this.tableData = result.data.rows; // 假设后端返回的数据结构包含 rows 字段存储当前页的数据
          this.totalData = result.data.total; // 假设后端返回的数据结构包含 total 字段存储总数据量
        } else {
          this.showError('请求不成功1');
        }
      } catch (error) {
        this.showError('请求失败2');
      }
    },
    async handleDelete(index, row) {
      try {
        if (!row.id) {
          this.showError('该班级没有唯一标识符，无法删除');
          return;
        }
        await axios.delete(`http://localhost:8080/class/${row.deptId}`);
        this.tableData.splice(index, 1);
        this.showSuccess('删除成功');
        this.handlePageChange(this.currentPage);
      } catch (error) {
        this.showError('删除失败，请检查网络或联系管理员');
      }
    },
    handleAdd() {
      this.addDialogVisible = true;
    },
    async submitAdd() {
  try {
    if (!this.newClass.name.trim()) {
      this.showError('班级名称不能为空');
      return;
    }
    // 修正变量名
    const match = this.newClass.name.match(/\d+/);
    this.newClass.deptId = match? parseInt(match[0], 10) : null;
    const response = await axios.post('http://localhost:8080/class', this.newClass);
    const result = response.data;
    if (result.code === 1 && result.msg === "success") {
      this.addDialogVisible = false;
      // 等待 handlePageChange 完成
      await this.handlePageChange(this.currentPage);
      this.showSuccess('新增成功');
    } else if (result.code === 2) {
      this.showError('该班级已存在,请重新输入班级信息');
    } else {
      this.showError('新增不成功，请检查网络或联系管理员');
    }
  } catch (error) {
    // 显示更详细的错误信息
    console.error(error);
    this.showError('不允许添加班级，发生错误：' + error.message);
  }
},
    showError(message) {
      // 使用 element-ui 的 Message 组件
      this.$message.error(message);
    },
    showSuccess(message) {
      // 使用 element-ui 的 Message 组件
      this.$message.success(message);
    }
  },
  mounted() {
    this.fetchData();
  }
};
</script>